from sqlalchemy.orm import Session
from app.database.database import SessionLocal, engine, Base
from app.database.models.base import User, Role, Permission, RolePermission
from app.database.models.erp import (
    # 公共业务信息相关的类
    Carrier, Airport, Airplane, HotelInfo,
    # ERP系统相关的类
    WorkArea, WorkAreaTransaction,
    # 客户档案相关的类
    CustomerProfile, CustomerPassenger, CustomerTelNo, CustomerAddress,
    # 订单相关的类
    AirticketOrder, AirticketOrderPassenger, AirticketOrderFlight,
    HotelOrder, HotelOrderPassenger, ElevyStamp
)
from app.core.security import get_password_hash
from datetime import datetime

def init_db():
    # 创建所有表
    Base.metadata.create_all(bind=engine)
    
    db = SessionLocal()
    try:
        # 检查是否已经初始化
        if db.query(User).first():
            print("数据库已经初始化，跳过...")
            return

        # 创建默认角色
        admin_role = Role(
            name="admin",
            description="System Administrator"
        )
        db.add(admin_role)
        db.commit()
        db.refresh(admin_role)

        # 创建默认权限
        admin_permission = Permission(
            name="all",
            code="all",
            description="All permissions"
        )
        db.add(admin_permission)
        db.commit()
        db.refresh(admin_permission)

        # 创建角色-权限关联
        role_permission = RolePermission(
            role_id=admin_role.id,
            permission_id=admin_permission.id
        )
        db.add(role_permission)
        db.commit()

        # 创建默认工作区：旅行社ERP平台
        default_workarea = WorkArea(
            Name="旅行社ERP平台",
            EnglishName="Travel Agency ERP Platform",
            LicenseNo="PLATFORM001",
            ManagerName="系统管理员",
            ManagerUserNames="admin",
            TelNo="852-12345678",
            CityCode="HK",
            Address="香港特别行政区",
            ResellerRank="S",  # 最高级别
            Memo="系统默认工作区",
            Balance=1000000.00,  # 充足的初始余额
            PDFName="旅行社ERP平台",
            PDFAddress="香港特别行政区",
            PDFContactName="系统管理员",
            PDFTelNo="852-12345678",
            PDFEmail="admin@travelagent.com"
        )
        db.add(default_workarea)
        db.commit()
        db.refresh(default_workarea)

        # 创建系统管理员账号
        admin_user = User(
            email="admin@travelagent.com",
            username="admin",
            hashed_password=get_password_hash("admin123"),
            role="admin",
            workarea_id=default_workarea.ID,  # 使用默认工作区ID
            is_active=True
        )
        db.add(admin_user)
        
        # 添加一些基础数据
        # 添加一个示例承运人
        sample_carrier = Carrier(
            Code="CX",
            FullName="国泰航空公司",
            BriefName="国泰航空",
            TicketNoCode="160",
            ServiceTel="852-2747-3333",
            Memo="香港主要航空公司"
        )
        db.add(sample_carrier)

        # 添加一个示例机场
        sample_airport = Airport(
            Code="HKG",
            Name="香港国际机场",
            CityName="香港",
            CityPinYin="XiangGang",
            CounterAddress="香港大屿山香港国际机场",
            IsInternational=True,
            EglishName="Hong Kong International Airport",
            FullName="X 香港香港国际机场"
        )
        db.add(sample_airport)

        # 添加一个示例飞机型号
        sample_airplane = Airplane(
            PlaneModel="B777",
            Shape="宽体机",
            Company="波音",
            MinSeatCount=300,
            MaxSeatCount=396,
            PhotoUrl="https://example.com/b777.jpg"
        )
        db.add(sample_airplane)

        # 添加一个示例酒店
        sample_hotel = HotelInfo(
            HotelId="HK001",
            HotelName="香港丽思卡尔顿酒店",
            HotelEnglishName="The Ritz-Carlton Hong Kong",
            RankCode="5",
            Address="香港九龙柯士甸道西1号环球贸易广场",
            TrafficInfo="港铁九龙站直达",
            Floor="102-118",
            RoomQuantity="312",
            QuotaPerDays="50",
            Promotion="无",
            Telephone="852-2263-2263",
            BasicInfo="位于环球贸易广场102-118层",
            Guarantee="需要信用卡担保",
            Currency="HKD",
            CityCode="HK",
            FAX="852-2263-2260",
            Exceptive="无",
            AgentCommisionRate="10%",
            GuaranteePolicy="标准担保政策",
            Policy="标准政策",
            YLPolicy="预留政策",
            OpenDate="2011-03-29",
            FitMent="豪华装修",
            PositionOfRemark="位于西九龙"
        )
        db.add(sample_hotel)

        db.commit()
        print("数据库初始化完成！")

    except Exception as e:
        print(f"初始化过程中出错: {str(e)}")
        db.rollback()
        raise
    finally:
        db.close()

if __name__ == "__main__":
    init_db() 